package com.szholly.utils.freemarker.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.szholly.utils.spring.springmvc.route.FunctionInfo;
import com.szholly.utils.util.StringUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 定义文本裁切标签
 */
@Component("directive_textcut")
public class TextCutDirective implements TemplateDirectiveModel, IDirective {

	public static final String PARAM_S = "s";
	public static final String PARAM_LEN = "len";
	public static final String PARAM_APPEND = "append";

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		String s = DirectiveUtils.getString(PARAM_S, params);
		Integer len = DirectiveUtils.getInt(PARAM_LEN, params);
		String append = DirectiveUtils.getString(PARAM_APPEND, params);
		if (s != null) {
			Writer out = env.getOut();
			if (len != null) {
				out.append(StringUtils.textCut(s, len, append));
			} else {
				out.append(s);
			}
		}
	}
	
	@Override
	public FunctionInfo getFunctionInfo() {
		String paraInfo = "s：当前文本 <br/>len：长度<br/>append：替换内容"
				+"示例：<@textcut s='<aaaaaa>' len=20 append='...' />";
		FunctionInfo info = new FunctionInfo("textcut", 1, "ͨ基础",
				"文本裁切标签", paraInfo);
		return info;
	}
}
